import MainLayout from "@/components/Layout";
import HttpUtils from "@/utils/HttpUtils";
import { Divider } from "antd";
import {
  AppContainer,
  Button,
  IconFont,
  Input,
  Select,
  Slider,
  Tooltip,
  Checkbox,
} from "knowdesign";
import React, { useEffect, useRef, useState } from "react";
import api from "./api";
import { sortFieldList, sortTypes, statusFilters } from "./config";
import "./index.less";
import ClusterList from "./List";

interface ClustersState {
  liveCount: number;
  downCount: number;
  total: number;
}

interface ClustersHealthState {
  deadCount: number;
  goodCount: number;
  mediumCount: number;
  poorCount: number;
  total: number;
  unknownCount: number;
}

export interface SearchParams {
  healthState?: number[];
  checkedKafkaVersions?: string[];
  sortInfo?: {
    sortField: string;
    sortType: string;
  };
  keywords?: string;
  clusterStatus?: number[];
  isReloadAll?: boolean;
}

const CheckboxGroup = Checkbox.Group;
const { Option } = Select;

const Index = () => {
  const [global] = AppContainer.useGlobalValue();
  const [stateInfo, setStateInfo] = React.useState<ClustersState>({
    downCount: 0,
    liveCount: 0,
    total: 0,
  });

  // TODO: 首次进入因 searchParams 状态变化导致获取两次列表数据的问题
  const [searchParams, setSearchParams] = React.useState<SearchParams>({
    keywords: "",
    checkedKafkaVersions: [],
    sortInfo: {
      sortField: "id",
      sortType: "asc",
    },
    clusterStatus: [1, 2],
    healthState: [-1, 0, 1, 2, 3],
    // 是否拉取当前所有数据
    isReloadAll: false,
  });

  const searchKeyword = useRef("");
  const isReload = useRef(false);

  const updateSearchParams = (params: SearchParams) => {
    getExecutorState();
    setSearchParams((curParams) => ({
      ...curParams,
      isReloadAll: false,
      ...params,
    }));
  };

  const searchParamsChangeFunc = {
    // 健康分改变
    onSilderChange: (value: number[]) =>
      updateSearchParams({
        healthState: value,
      }),
    // 排序信息改变
    onSortInfoChange: (type: string, value: string) =>
      updateSearchParams({
        sortInfo: {
          ...searchParams.sortInfo,
          [type]: value,
        },
      }),
    // Live / Down 筛选
    onClusterStatusChange: (list: number[]) =>
      updateSearchParams({
        clusterStatus: list,
      }),
    // 集群名称搜索项改变
    onInputChange: () =>
      updateSearchParams({
        keywords: searchKeyword.current,
      }),
    // 集群版本筛选
    onChangeCheckGroup: (list: string[]) => {
      updateSearchParams({
        checkedKafkaVersions: list,
        isReloadAll: isReload.current,
      });
      isReload.current = false;
    },

    fresh: () => {
      updateSearchParams(searchParams);
    },
  };

  const getExecutorState = () => {
    HttpUtils.get(api.executorCount).then((data) => {
      if (data?.code === 200) {
        setStateInfo(data?.data);
      }
    });
  };

  useEffect(() => {
    getExecutorState();
  }, []);

  return (
    <>
      <MainLayout>
        <div className="multi-cluster-page" id="scrollableDiv">
          <div className="multi-cluster-page-fixed">
            <div className="content-container">
              <div className="multi-cluster-header">
                <div className="cluster-header-card">
                  <div className="cluster-header-card-bg-left"></div>
                  <div className="cluster-header-card-bg-right"></div>
                  <h5 className="header-card-title">
                    执行器<span className="chinese-text"> 总数</span>
                  </h5>
                  <div className="header-card-total">{stateInfo.total}</div>
                  <div className="header-card-info">
                    <div className="card-info-item card-info-item-live">
                      <div>
                        live
                        <span className="info-item-value">
                          <em>{stateInfo.liveCount}</em>
                        </span>
                      </div>
                    </div>
                    <div className="card-info-item card-info-item-down">
                      <div>
                        down
                        <span className="info-item-value">
                          <em>{stateInfo.downCount}</em>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="cluster-header-filter">
                  <div className="header-filter-top">
                    <div className="header-filter-top-input">
                      <Input
                        onPressEnter={searchParamsChangeFunc.onInputChange}
                        onChange={(e) =>
                          (searchKeyword.current = e.target.value)
                        }
                        allowClear
                        bordered={false}
                        placeholder="请输入执行器名称进行搜索"
                        suffix={
                          <IconFont
                            className="icon"
                            type="icon-fangdajing"
                            onClick={searchParamsChangeFunc.onInputChange}
                          />
                        }
                      />
                    </div>
                  </div>

                  <div className="header-filter-bottom">
                    <div className="header-filter-bottom-item header-filter-bottom-item-checkbox">
                      <h3 className="header-filter-bottom-item-title">
                        版本分布
                      </h3>
                      <div className="header-filter-bottom-item-content flex">
                        {/* {existKafkaVersion.length ? (
                            <CustomCheckGroup
                              kafkaVersions={existKafkaVersion}
                              onChangeCheckGroup={searchParamsChangeFunc.onChangeCheckGroup}
                            />
                          ) : null} */}
                      </div>
                    </div>
                    <div className="header-filter-bottom-item header-filter-bottom-item-slider">
                      {/* <h3 className="header-filter-bottom-item-title title-right">
                        健康状态
                      </h3>
                      <Tooltip
                        title="test"
                        overlayClassName="cluster-health-state-tooltip"
                      >
                        <div
                          className="header-filter-bottom-item-content"
                          id="clusters-slider"
                        >
                          <Slider
                            dots
                            range={{ draggableTrack: true }}
                            step={1}
                            max={5}
                            // marks={healthSorceList}
                            // value={sliderInfo.value}
                            tooltipVisible={false}
                            // onChange={(value: [number, number]) => {
                            //   if (value[0] !== value[1]) {
                            //     const result = [];
                            //     for (let i = 0; i < value[1] - value[0]; i++) {
                            //       const val = sliderValueMap[(value[1] - i) as keyof typeof sliderValueMap];
                            //       result.push(`${val.name}: ${clustersHealthState?.[val.key as keyof ClustersHealthState]}`);
                            //     }
                            //     setSliderInfo({
                            //       value,
                            //       desc: result.reverse().join(', '),
                            //     });
                            //   }
                            // }}
                            // onAfterChange={(value: [number, number]) => {
                            //   const result = [];
                            //   for (let i = 0; i < value[1] - value[0]; i++) {
                            //     const val = sliderValueMap[(value[1] - i) as keyof typeof sliderValueMap];
                            //     result.push(val.code);
                            //   }
                            //   searchParamsChangeFunc.onSilderChange(result);
                            // }}
                          />
                        </div>
                      </Tooltip> */}
                    </div>
                  </div>
                </div>
              </div>
              <div className="multi-cluster-filter">
                <div
                  className="multi-cluster-filter-select"
                  style={{ alignItems: "center" }}
                >
                  <div
                    className="refresh-icon"
                    style={{ marginLeft: 4 }}
                    onClick={() => {
                      searchParamsChangeFunc.fresh();
                    }}
                  >
                    <IconFont className="icon" type="icon-shuaxin1" />
                  </div>

                  <Divider
                    type="vertical"
                    style={{ height: "2em", marginRight: 12 }}
                  />
                  {/* <Select
                    onChange={(value) =>
                      searchParamsChangeFunc.onSortInfoChange(
                        "sortField",
                        value
                      )
                    }
                    defaultValue="HealthState"
                    style={{ width: 170, marginRight: 12 }}
                  >
                    {sortFieldList.map((item) => (
                      <Option key={item.value} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select> */}
                  <Select
                    onChange={(value) =>
                      searchParamsChangeFunc.onSortInfoChange("sortType", value)
                    }
                    defaultValue="asc"
                    style={{ width: 170 }}
                  >
                    {sortTypes.map((item) => (
                      <Option key={item.value} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </div>
                <div className="multi-cluster-filter-checkbox">
                  <CheckboxGroup
                    options={statusFilters}
                    value={searchParams.clusterStatus}
                    onChange={searchParamsChangeFunc.onClusterStatusChange}
                  />
                </div>
              </div>
              {/* <AccessCluster /> */}
            </div>
          </div>
          <div className="multi-cluster-page-dashboard">
            <ClusterList
              searchParams={searchParams}
              // showAccessCluster={showAccessCluster}
              // getPhyClusterState={getPhyClusterState}
              // getExistKafkaVersion={getExistKafkaVersion}
            />
          </div>
        </div>
      </MainLayout>
    </>
  );
};

export default Index;
